package tmi.li.txwthrsmall;



import java.util.Locale;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.RemoteViews;


import tmi.li.txwthrsmall.R;



public class TxWthrSmallProvider extends AppWidgetProvider {
	//private static String TAG = "tmi.li.txwthrsmall.TxWthrProvider";
	
	@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		TxPref txpref = new TxPref();
		for(int i = 0; i < appWidgetIds.length; i++) {
			if(txpref.getMisc(context, appWidgetIds[i], TxPref.FLCOLOR) != null)  {
				Intent test = new Intent(context, Update.class);
				test.putExtra("Id", appWidgetIds[i]);
				context.startService(test);
				updateWidget(context, appWidgetManager, appWidgetIds[i]);
			}     	
		}

    }
	
		
    static public void updateWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
    	
    	//getting the Preferences of the widget
    	TxPref txpref = new TxPref();
    	
    	// if s == null the Configuration Dialog hasnt ended yet, so do nothin
    	String hex;
    	if((hex = txpref.getMisc(context, appWidgetId, TxPref.FLCOLOR) )!= null ) {	
    		String bhex = txpref.getMisc(context, appWidgetId, TxPref.BCOLOR);
    		
    		//if prefs.length < 4 then the build update for the first time isnt finished
    		String current;
	        if((current = txpref.getMisc(context, appWidgetId, TxPref.CURRENT)) != null) {
	        	String desc = txpref.getMisc(context, appWidgetId, TxPref.DESC);
	        	String desc2;
		        if((desc2 = txpref.getMisc(context, appWidgetId, TxPref.DESC2)) == null) 
		        		desc2 = "";
		        
		    	//getting the Widget views
		        RemoteViews views = null;   
		        views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		        
		        //if the sdk version is >= 8 aka android 2.2 froyo set the Background color
		        if(VERSION.SDK_INT >= 8) {
		        	views.setInt(R.id.lWidget, "setBackgroundColor", Color.parseColor(bhex));
		        }
		        
		        //setting the current temperature and description
		        views.setTextViewText(R.id.TextView01, current);
		        views.setTextViewText(R.id.TextView02, desc);
		        views.setTextViewText(R.id.TextView03, desc2);
		        
		        //setting the Font Color for the Widget
		        views.setTextColor(R.id.TextView01, Color.parseColor(hex));
		        views.setTextColor(R.id.TextView02, Color.parseColor(txpref.getMisc(context, appWidgetId, TxPref.FTCOLOR)));
		        views.setTextColor(R.id.TextView03, Color.parseColor(txpref.getMisc(context, appWidgetId, TxPref.FBCOLOR)));
		        
		        //setting the OnClick Pending INtent for the whole Layout
		        String appname;
		        if((appname = txpref.getMisc(context, appWidgetId, TxPref.APPNAME)) != null) {
		           	Intent intent = new Intent(Intent.ACTION_MAIN);
		        	intent.setComponent(ComponentName.unflattenFromString(appname));
		        	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		        	views.setOnClickPendingIntent(R.id.lWidget, pendingIntent);
		        }
						        
				//updating the widget via the widget manager
		        appWidgetManager.updateAppWidget(appWidgetId, views);
		        
	        }else {
	        	//no updates yet so try to get new ones asap
	        	Intent test = new Intent(context, Update.class);
				test.putExtra("Id", appWidgetId);
				context.startService(test);
	        }
    	}
    }
    
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
    	
        // When the user deletes the widget, delete the preference associated with it.
    	TxPref txpref = new TxPref();
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            txpref.deleteMisc(context, appWidgetIds[i]);
        }
    }
	
	public static class Update extends Service {
 
	    @Override
	    public void onStart(Intent intent, int startId) {
	    	
			//registering TxWthrReceiver for various Broadcasts 
	    	IntentFilter it = new IntentFilter(Intent.ACTION_SCREEN_ON);
			BroadcastReceiver mReceiver = new TxWthrSmallReceiver();
			this.registerReceiver(mReceiver, it);
			it = new IntentFilter(TxWthrSmallFinals.UPDATE);
			this.registerReceiver(mReceiver, it);
	    	
	    	
	        // Build the widget update && send a custom Broadcast so the widget is updated asap when the update is ready
			if(intent.hasExtra("Id")) {
				Bundle extras = intent.getExtras();
				int id = extras.getInt("Id");
				buildUpdate(this, id);
				this.sendBroadcast(new Intent(TxWthrSmallFinals.UPDATE));
			}
			
			
	    }

	    @Override
	    public IBinder onBind(Intent intent) {
	        return null;
	    }
	    

	    @SuppressWarnings("static-access")
		public void buildUpdate(Context context, int id) {
	        try {
	        	
	        	//updating the widget and appending the new infos to the old str
	        	//so we can save it again in the preferences
	        	TxPref txpref = new TxPref();
	        	WeatherUpdate updt = new WeatherUpdate();
	        	
	        	String woeid = txpref.getMisc(context, id, TxPref.WOEID);
	        	String format = txpref.getMisc(context, id, TxPref.FORMAT);
		        updt.getRss(woeid, format);
		        //FIXME : validate updt.desc/updt.current/updt.desc2
		        //alsdfjasdfaisejfasefsa 
		        String lang;
		        if((lang = txpref.getMisc(context, id, TxPref.LANG)) != null) {
		        	if(lang == "null") {
		        		Locale local = new Locale("en");
		        		local = local.getDefault();
		        		lang = checkLocal(local.toString());
		        		txpref.saveMisc(context, id, TxPref.LANG, lang);
		        	}
		        	Locale locale2 = new Locale(lang); 
		            Locale.setDefault(locale2);
		            Configuration config2 = new Configuration();
		            config2.locale = locale2;
		         // updating locale
		            this.getResources().updateConfiguration(config2, null);
		        }
		        String desc = getDesc(updt.wcode);
		        desc = desc.toUpperCase();
		        if(desc.contains(";")) {
		        	String[] str = desc.split(";");
		        	updt.desc = str[0];
		        	updt.desc2 = str[1];
		        }else {
		        	updt.desc = desc;
		        	updt.desc2= "";
		        }
		        txpref.saveMisc(context, id, TxPref.CURRENT, updt.current);
		        txpref.saveMisc(context, id, TxPref.DESC, updt.desc);
		        txpref.saveMisc(context, id, TxPref.DESC2, updt.desc2);
		        
		        
	        } catch (Exception e) {

	        }   
	       	        
	    }
	    
	    public String checkLocal(String str) {
	    	if(str.contains("en")) {
	    		return "en";
	    	}else if (str.contains("de")){
	    		return "de";
	    	}else if (str.contains("fr")) {
	    		return "fr";
	    	}else if(str.contains("ru")) {
	    		return "ru";
	    	}else {
	    		return "en";
	    	}
	    }
	    
	    public String getDesc(String wcode) {
	    	int _wcode = Integer.valueOf(wcode);
	    	wcode = Integer.toHexString(_wcode);
	    	String hex = "7f0600";
	    	if(_wcode < 16)
	    		return getString(Integer.parseInt(hex+"0"+wcode,16));
	    	return getString(Integer.parseInt(hex+wcode,16));
	    }
	    
	}

		
}